from fdfs_client.client import Fdfs_client

from django.conf import settings
from rest_framework import serializers

from goods.models import Brand


class BrandSerializer(serializers.ModelSerializer):
    class Meta:
        model = Brand
        fields = "__all__"

    def create(self, validated_data):
        logo = validated_data["logo"]
        client = Fdfs_client(settings.FDDS_CIENT)  # 上传
        result = client.upload_by_buffer(logo.read())
        # 判断是否上传成功
        if result["Status"] != "Upload successed.":
            raise serializers.ValidationError("上传图片失败")
        image_name = result["Remote file_id"]
        validated_data["logo"] = image_name.replace('\\', '/')
        return Brand.objects.create(**validated_data)
        # img_url = settings.BASE_URL + result["Remote file_id"]
